<template>
	<div id="company-list">
		<el-form class="demo-form-inline">
			<el-form-item label="机构名称" v-if="isPid">
				<casader :pid="form.pid" ref="child"></casader>
			</el-form-item>
			<br />
			<el-form-item>
				<el-button type="primary" @click="onSubmit">查询</el-button>
				<el-button type="primary"  style="background:#ff9800; border-color:#ff9800;" @click="downLoads">下载</el-button>
				<el-button style="background:#ff9800; border-color:#ff9800;" type="primary" @click="addCom">添加单位</el-button>
				<!-- <el-button type="primary" @click="addPeo">批量导入</el-button> -->
			</el-form-item>
		</el-form>
		<div class="table">
			 <el-table :data="tableData" style="width: 100%"   @selection-change="handleSelectionChange">
				<el-table-column type="index" width="70" label="序号">
					<template slot-scope="scope">
						{{ (currentPage-1)*pageSize+scope.$index+1 }}
					</template>
				</el-table-column>
				<el-table-column prop="name"  label="单位名称">
					<template slot-scope="scope">
						<div>
							{{ scope.row.name }}
							<i v-if="currentPage==1&&scope.$index==0" style="vertical-align: text-bottom;" @click="pAdd(scope.row.id)" class="addicon el-icon-circle-plus"></i>
						</div>
					</template>
				</el-table-column>
				<el-table-column prop="pname"  label="所属单位"></el-table-column>
				<el-table-column prop="num" label="单位人数" width="100"></el-table-column>
				<el-table-column prop="teacherCount" label="讲师数量" width="100"></el-table-column>
				<el-table-column prop="courseCount" label="讲座数量" width="100"></el-table-column>
				<el-table-column label="操作" align="center" width="150">
					<template slot-scope="scope">
						<el-button
						size="mini"
						type="success"
						@click="rowEdit(scope.row.id)" style="background:#42a7ff; border-color:#42a7ff;">编辑</el-button>
						<el-button
						size="mini"
						type="danger"
						@click="rowDelete( scope.row.id)">删除</el-button>
					</template>
				</el-table-column>
			</el-table>
			<el-pagination
			v-if="tableData.length>0"
				@size-change="handleSizeChange"
				@current-change="handleCurrentChange"
				:current-page="currentPage"
				:page-size="pageSize"
				layout="total, prev, pager, next, jumper"
				:total="totalCount"
			></el-pagination>
		</div>


		 <el-dialog :close-on-click-modal="false" title="批量导入" :visible.sync="pAddDialog" width='400px'>
			 <el-form  :model="form" class="demo-form-inline">
				<el-form-item label="">
					<el-button  type="primary" style="background:#42a7ff; border-color:#42a7ff;">
						<a style="color:#fff;" href="http://tsw.ithyxy.com/images/%E5%AF%BC%E5%85%A5%E6%9C%BA%E6%9E%84%E6%A8%A1%E6%9D%BF.xlsx">下载模板</a>
					</el-button>
					<el-upload
						style="display:inline-block;"
						class="upload-demo"
						action="/lec/learn/class/import"
						:on-success="uploadSuccess"
						:on-error="uploadError"
						:limit="1"
						:data="{pid:uploadPid}"
						:show-file-list="false"
						>
					<el-button  type="primary">点击上传</el-button>
					<!-- <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div> -->
					</el-upload>
				</el-form-item>
			 </el-form>
		     <!-- <div style="width:70px;margin:0 auto" >
				<el-button size="small" type="primary" @click="saveAdd">关闭</el-button>
		     </div> -->

		 </el-dialog>

		 <el-dialog :close-on-click-modal="false" title="添加单位" :visible.sync="dialogAdd" width='800px' @close='close'  >
			 <el-form  :model="form" class="demo-form-inline">
				<el-form-item label="上级单位">
					<casader :pid="form.pid" ref="caAdd"></casader>
				</el-form-item>
				 <el-form-item label="单位名称">
					<el-input v-model="form.name" placeholder="单位名称"></el-input>
				</el-form-item>
				 <el-form-item label="单位人数">
					<el-input v-model="form.num" placeholder="单位人数"></el-input>
				</el-form-item>
			 </el-form>
		     <div style="width:70px;margin:0 auto" >
				<el-button type="primary" @click="saveAdd">保存</el-button>
		     </div>

		 </el-dialog>
		  <el-dialog :close-on-click-modal="false" title="修改" :visible.sync="dialogEdit" width='800px'>
			 <el-form  :model="formEdit" class="demo-form-inline">
				 <el-form-item label="上级单位">
					<casader :pid="form.pid" ref="caEdit"></casader>
				</el-form-item>
				 <el-form-item label="单位名称">
					<el-input v-model="formEdit.name" placeholder="单位名称"></el-input>
				</el-form-item>
				 <el-form-item label="单位人数">
					<el-input v-model="formEdit.num" placeholder="单位人数"></el-input>
				</el-form-item>
			 </el-form>
		     <div style="width:70px;margin:0 auto" >
				<el-button type="primary" @click="saveEdit">保存</el-button>
		     </div>

		 </el-dialog>
	</div>
</template>

<script>
let id = 0;
import Casader from '../components/cascaderD';
	export default {
  	components: { Casader },
		 data() {
            return {
				pid:'',
				//是否读取完pid
				isPid:false,
				uploadPid:'',
				aa:'',
				pAddDialog:false,
				//添加
				dialogAdd:false,
				form:{
					//上级单位id
					pid:0,
					//单位名称
					name:'',
					//单位人数
					num:'',
				},
				//修改
				dialogEdit:false,
				formEdit:{
					//单位id
					id:'',
					//上级单位id
					pid:0,
					//单位名称
					name:'',
					//单位人数
					num:'',
				},
				currentPage: 1,
				pageSize: 10,
				totalCount: 1000,
				tableData:[],
				a:[
					{
						x:5,
						y:6
					}
				],
				aid:0,
				selectedOptions: [1,2,4,7],
				props: {
					lazy: true,
					checkStrictly:true,
					lazyLoad (node, resolve) {
						const { level } = node;
						setTimeout(() => {
						const nodes = Array.from({ length: level + 1 })
							.map(item => ({
							value: ++id,
							label: `选项${id}`,
							leaf: level >= 15
							}));
						console.log(nodes,22);
						// 通过调用resolve将子节点数据返回，通知组件数据加载完成
						resolve(nodes);
						console.log(self.aid);
						}, 50);
					}
				},

            }
		},
		computed:{
			downloadId(){
				if(this.$refs.child){
					return this.$refs.child.cx()
				}
				else{
					return 0;
				}
			},
		},
		created() {
		},
		mounted(){
			this.init();
		},
		methods:{
			 //回填
			// a(){
			// 	//this.$refs.child.$emit('changeValue2','发送给方法一的数据') // 方法1:触发监听事件
			// 	let b = ["北京市", "北京城区", "怀柔区", "泉河街道"];
			// 	this.$refs.child.changeValue2(b) // 方法2:直接调用
			// },
			// //获取
			// b(){
			// 	let res = this.$refs.child.cx() // 方法2:直接调用
			// 	console.log(res);
			// },
			init(){
				this.getPid();
			},
			//获取pid
			getPid(){
				let self = this;
				self.$http.get('/admin/pid').then((response) => {
                    let res = response.data
                    if(res.code == '200') {
						console.log(res,111222)
						self.isPid = true;
						self.form.pid = res.data;
						self.pid = res.data;
						console.log(self.form.pid,2222222);
						self.$nextTick(function(){
							self.getList();
						});

                    }else {
						self.$message.error(res.message)
					}
                })
			},
			uploadSuccess(res){
				this.$message.success(res.message);
				this.pAddDialog = false;
			},
			uploadError(res){
				this.$message.error(res.message)
			},
			pAdd(pid){
				let self = this;
				self.uploadPid = pid;
				self.pAddDialog = true;
			},
			changeId(val,b){
				console.log(val,22222);
				console.log(b,22222);
			},
			handleItemChange(val) {
				console.log(val,111);
				// console.log('active item:', val);
				// setTimeout(_ => {
				// if (val.indexOf('江苏') > -1 && !this.options2[0].cities.length) {
				// 	this.options2[0].cities = [{
				// 	label: '南京'
				// 	}];
				// } else if (val.indexOf('浙江') > -1 && !this.options2[1].cities.length) {
				// 	this.options2[1].cities = [{
				// 	label: '杭州'
				// 	}];
				// }
				// }, 300);
			},
			//查询下级单位
			getSelect(id){
				let self = this;
				if(!id){
					id = '';
				}
				self.$http.get('/learn/class/sub?id='+id).then((response) => {
                    let res = response.data
                    if(res.code == '200') {
						// data:[
						// 	{
						// 		name:'',
						// 		id:1
						// 	}
						// ]
						self.tableData = res.data.content
						self.totalCount = res.data.total
						console.log(self.tableData,111)

                    }else {
						self.$message.error(res.message)
					}


                })
			},
			//获取列表
			getList(){
				let self = this;
				let id = this.$refs.child.cx();
				console.log(id,222222);
				console.log(self.form.pid,223344);
				//强制刷新级联
				self.$refs.child.modalKey+=1;
				console.log(id,323232);
				self.$http.get('/learn/class/list?id='+id+'&pageNum='+self.currentPage+'&pageSize='+self.pageSize).then((response) => {
                    let res = response.data
                    if(res.code == '200') {
						console.log(res,1);
						self.tableData = res.data.content
						self.totalCount = res.data.total
						console.log(self.tableData,111)

                    }else {
						self.$message.error(res.message)
					}


                })
			},
			handleSelectionChange(){},
			//查询
			onSubmit(){
				this.currentPage = 1;
				this.getList();
			},
			//下载
            // downLoads(){
            //     let self = this
			// 	let pid = self.$refs.child.cx();
			// 	let url = `/oa/learn/class/download?id=${pid}`;
			// 	let downloadElement = document.createElement('a');
			// 	downloadElement.style.display = 'none';
			// 	downloadElement.href = url;
			// 	document.body.appendChild(downloadElement);
			// 	downloadElement.click(); //点击下载
			// 	document.body.removeChild(downloadElement); //下载完成移除元素
			// },
			//下载
            downLoads(){
                let self = this
				let pid = self.$refs.child.cx();
				const loading = self.$loading({
					lock: true,
					text: '加载中...',
					spinner: 'el-icon-loading',
					background: 'rgba(0, 0, 0, 0.7)'
				});
                self.$http.post(`/learn/class/download?pid=${pid}`,{
                },{responseType: 'blob'}) .then((response) => {
                    let blob = new Blob([response.data], {type: response.headers['content-disposition']});
                    //console.log(response.headers['content-disposition'],55555);
                    let fileName = '单位列表.xlsx'
                    let url = window.URL.createObjectURL(blob);
                    let downloadElement = document.createElement('a');
                    downloadElement.style.display = 'none';
                    downloadElement.href = url;
                    downloadElement.download = fileName; //下载后文件名
                    document.body.appendChild(downloadElement);
                    downloadElement.click(); //点击下载
                    document.body.removeChild(downloadElement); //下载完成移除元素
					window.URL.revokeObjectURL(url);
					loading.close();
					console.log(1234);
                }).catch(err => {
                    console.log(err)
					loading.close();
                })
            },
			//关闭
			close(){
				let self = this;
				self.form.pid = self.pid;
				self.form.name = '';
				self.form.num = '';
				//强制刷新级联
				self.$refs.caAdd.modalKey+=1;
				self.$refs.caEdit.modalKey+=1;
				console.log(5645);
			},
			//添加单位
			addCom(){
				this.dialogAdd = true;
			},
			//添加单位保存
			saveAdd(){
				let self = this;

				let pid = this.$refs.caAdd.cx();
				console.log(pid,11);
				if(self.form.pid == ''){
					//self.$message.warning('请选择上级单位')
					//return
                }else if (self.form.name == '') {

					self.$message.warning('请输入单位名称')
					return
				}else if (self.form.num == '') {

					self.$message.warning('请输入单位人数')
					return
				}

                self.$http.post('/learn/class/add',{
				    pid: pid,
					name: self.form.name,
					num: self.form.num

				}).then((response) => {
                    let res = response.data
                    if(res.code == '200') {
						self.$message.success('保存成功')
						self.dialogAdd = false
						self.getList()
                    }else {
						self.$message.error(res.message)
					}
                }).catch(err => {
                    self.$message.error(res.message)
                })
			},
			//修改单位
			rowEdit(id){
				let self = this;
				self.$http.get(`/learn/class/info?id=${id}`).then((response) => {
                    let res = response.data
                    if(res.code == '200') {
						console.log(res,222);
						let av = res.data.path;
						console.log(av,333);
						self.formEdit.id = id;
						self.formEdit.name = res.data.name;
						self.formEdit.num = res.data.num;
						// let newav = av.filter((item,index) => index > 0);
                        console.log(self.form.pid,234);
						self.$refs.caEdit.changeValue(av)

                    }else {
						self.$message.error(res.message)
					}


                })
				this.dialogEdit = true;
			},
			//编辑保存
			saveEdit(){
				let self = this
				let pid = this.$refs.caEdit.cx();
				if(self.formEdit.pid == ''){
					//self.$message.warning('请选择上级单位')
					//return
                }else if (self.formEdit.name == '') {

					self.$message.warning('请输入单位名称')
					return
				}else if (self.formEdit.num == '') {

					self.$message.warning('请输入单位人数')
					return
				}
				self.$http.post('/learn/class/update',{
				    pid: pid,
					name: self.formEdit.name,
					num: self.formEdit.num,
					id:self.formEdit.id

				}).then((response) => {
                    let res = response.data
                    if(res.code == '200') {
						self.$message.success('保存成功')
						self.dialogEdit = false
						this.getList()

                    }else {
						self.$message.error(res.message)
					}


                })


			},
			//删除单位
			rowDelete(id){
				let self = this
				self.$confirm('是否删除选中?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					self.$http.get('/learn/class/delete?id='+id).then((response) => {
						let res = response.data
						if(res.code == '200') {
							self.$message.success('删除成功')
							self.currentPage = 1;
							self.getList()

						}else {
							self.$message.error(res.message)
						}


					},(err) => {
						console.log('err');
					})
				}).catch(() => {
				})
			},
			//导入人数
			addPeo(){},
			//分页
			handleSizeChange: function (size) {
				this.pageSize = size;
			},
			handleCurrentChange: function(currentPage) {
				this.currentPage = currentPage
				this.getList();
			},
		},
	}
</script>

<style scoped>
.el-input>>>.el-input__inner{
	width: 350px;
}
/deep/ .el-table__body, /deep/ .el-table__header{
	width: auto!important;
}
.table{
	margin: 20px 0;
	width: 100%;
}
.el-pagination{
	text-align: right;
}
</style>
<style lang="scss">
	#company-list{
		.addicon{
			cursor:pointer;
			color:rgb(255, 152, 0);
			font-size:18px;
			padding:0 0 0 4px;
		}
	}
</style>
